package com.tongyi.lizhishop.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.classic.common.MultipleStatusView;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.constants.Constants;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tongyi.lizhishop.activitys.ConsumeItemDetailActivity;
import com.tongyi.lizhishop.beans.BillItemBean;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.AppStringUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.MessageApi;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ConsumeDetailFragment extends Fragment implements OnRefreshListener, OnLoadmoreListener {


    private int position;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multiple_status_view)
    MultipleStatusView multipleStatusView;
    Unbinder unbinder;

    private int currentPageIndex;
    private CommonAdapter<BillItemBean.ArrayBean> adapter;
    private List<BillItemBean.ArrayBean> itemData = new ArrayList<>();

    public ConsumeDetailFragment() {
    }


    public static ConsumeDetailFragment newInstance(int position, String param2) {
        ConsumeDetailFragment fragment = new ConsumeDetailFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = getArguments().getInt("position");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.multi_smartrefresh_recycleview, null, false);
        unbinder = ButterKnife.bind(this, view);
        initRefreshView();
        initRecyclerViewAndRefreshLayout();
        multipleStatusView.showLoading();
        loadData();
        return view;
    }

    private void initRecyclerViewAndRefreshLayout() {

        recyclerview.setLayoutManager(new LinearLayoutManager(this.getContext()));
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        adapter = new CommonAdapter<BillItemBean.ArrayBean>(this.getContext(), R.layout.activity_consume_detail, itemData) {
            @Override
            protected void convert(ViewHolder holder, final BillItemBean.ArrayBean o, int position) {
                ((SwipeMenuLayout) holder.getView(R.id.swipmenu)).setSwipeEnable(false);
                holder.setText(R.id.ddbh, "订单编号 : " + o.getBil_order());
                holder.setText(R.id.startTime, "发起时间 : " + AppStringUtils.getSafeTime("yyyy-MM-dd HH:mm:ss", o.getBil_starttime()));
                holder.setText(R.id.startUser, "发起用户 : " + o.getIphone());
                holder.setText(R.id.moneynumber, "¥ " + o.getBil_smoneyall());
                holder.setOnClickListener(R.id.l, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("bilid", o.getBil_id());
                        ActivityUtils.startActivity(bundle, ConsumeDetailFragment.this.getActivity(), ConsumeItemDetailActivity.class);
                    }
                });
            }

        };
        recyclerview.addItemDecoration(new DividerItemDecoration(getContext(), 1));
        recyclerview.setAdapter(adapter);

    }

    private void initRefreshView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableAutoLoadmore(true);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        currentPageIndex = 0;
        multipleStatusView.showContent();
        loadData();
    }

    public void loadData() {
        APIServiceManager.getInstance().create(MessageApi.class)
                .showBill(SPUtils.getInstance().getString("userid"),
                        AppStringUtils.getBillParams(position),
                        Constants.perPageSize,
                        currentPageIndex
                ).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<BillItemBean>() {
                    @Override
                    public void onSuccess(BillItemBean value) {
                        LogUtils.w("aa", value.getMsg(), value.getRes());
                        List<BillItemBean.ArrayBean> array = value.getArray();
                        if (array != null && array.size() != 0) {
                            if (currentPageIndex == 0) {
                                itemData.clear();
                            }
                            itemData.addAll(array);
                            adapter.notifyDataSetChanged();
                            multipleStatusView.showContent();
                            calculatePageIndexAndControlRefreshLayout(array);
                        } else {
                            //calculatePageIndexAndControlRefreshLayout(array);
                            refreshLayout.finishRefresh(0);
                            multipleStatusView.showEmpty();
                            LogUtils.w("shwoempty");
                        }

                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        multipleStatusView.showNoNetwork();
                        LogUtils.w("showfailure");
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        loadData();
    }


    /**
     * 计算下一次请求的页码
     *
     * @param array
     */
    public void calculatePageIndexAndControlRefreshLayout(List array) {
        if (currentPageIndex == 0) {
            refreshLayout.finishRefresh();
            refreshLayout.setLoadmoreFinished(false);
            if (array == null) {
                return;
            }
        } else {
            refreshLayout.finishLoadmore();

        }
        if (array.size() == Constants.perPageSize) {
            // may be has more
            currentPageIndex++;
        } else {
            //not more
            refreshLayout.setLoadmoreFinished(true);
        }


    }
}
